package com.ruoyi.vbze.service.impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.vbze.domain.Leaf;
import com.ruoyi.vbze.domain.Plant;
import com.ruoyi.vbze.mapper.PlantMapper;
import com.ruoyi.vbze.service.IPlantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 植株管理Service业务层处理
 * 
 * @author vbze
 * @date 2023-02-22
 */
@Service
public class PlantServiceImpl implements IPlantService 
{


    private static final Logger log = LoggerFactory.getLogger(PlantServiceImpl.class);

    @Autowired
    private PlantMapper plantMapper;

    /**
     * 查询植株管理
     * 
     * @param id 植株管理主键
     * @return 植株管理
     */
    @Override
    public Plant selectPlantById(Long id)
    {
        return plantMapper.selectPlantById(id);
    }

    /**
     * 查询植株管理列表
     * 
     * @param plant 植株管理
     * @return 植株管理
     */
    @Override
    public List<Plant> selectPlantList(Plant plant)
    {
        return plantMapper.selectPlantList(plant);
    }

    /**
     * 新增植株管理
     * 
     * @param plant 植株管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertPlant(Plant plant)
    {
        plant.setCreateTime(DateUtils.getNowDate());
        int rows = plantMapper.insertPlant(plant);
        insertLeaf(plant);
        return rows;
    }

    /**
     * 修改植株管理
     * 
     * @param plant 植株管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updatePlant(Plant plant)
    {
        plantMapper.deleteLeafByPlantNumber(plant.getPlantNumber());
        insertLeaf(plant);

        plant.setLastEditTime(DateUtils.getNowDate());


        return plantMapper.updatePlant(plant);
    }

    /**
     * 批量删除植株管理
     * 
     * @param ids 需要删除的植株管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePlantByIds(Long[] ids)
    {
        String[] plantNumbers = plantMapper.selectPlantNumbersByIds(ids);
        plantMapper.deleteLeafByPlantNumbers(plantNumbers);
        return plantMapper.deletePlantByIds(ids);
    }

    /**
     * 删除植株管理信息
     * 
     * @param id 植株管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePlantById(Long id)
    {
        plantMapper.deleteLeafByPlantNumber(selectPlantById(id).getPlantNumber());
        return plantMapper.deletePlantById(id);
    }

    /**
     * 新增叶片管理信息
     * 
     * @param plant 植株管理对象
     */
    public void insertLeaf(Plant plant)
    {
        List<Leaf> leafList = plant.getLeafList();
//        Long id = plant.getId();
        String plantNumber = plant.getPlantNumber();
        if (StringUtils.isNotNull(leafList))
        {
            List<Leaf> list = new ArrayList<Leaf>();
            for (Leaf leaf : leafList)
            {
                leaf.setPlantNumber(plantNumber);
                list.add(leaf);
            }
            if (list.size() > 0)
            {
                plantMapper.batchLeaf(list);
            }
        }
    }




    /**
     * 导入植株数据
     *
     * @param plantList 植株列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importPlant(List<Plant> plantList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(plantList) || plantList.size() == 0)
        {
            throw new ServiceException("导入植株数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (Plant plant : plantList)
        {
            try
            {
                // 验证是否存在这个地块
//                SysUser u = userMapper.selectUserByUserName(block.getUserName());
                Plant p = plantMapper.selectPlantByPlantNumber(plant.getPlantNumber());
                if (StringUtils.isNull(p))
                {
//                    BeanValidators.validateWithException(validator, block);
//                    block.setPassword(SecurityUtils.encryptPassword(password));
                    plant.setCreateBy(operName);
                    plant.setLastEditor(operName);
                    plant.setUpdateBy(operName);
                    this.insertPlant(plant);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、植株 " + plant.getPlantNumber() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
//                    BeanValidators.validateWithException(validator, block);
//                    checkUserAllowed(block);
//                    checkUserDataScope(block.getUserId());
//                    block.setUpdateBy(operName);
                    plant.setUpdateBy(operName);
                    plant.setLastEditor(operName);
                    this.updatePlant(plant);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、植株 " + plant.getPlantNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、植株 " + plant.getPlantNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、植株 " + plant.getPlantNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
